package com.tanhua.manage.interceptor;

import com.tanhua.manage.domain.Admin;
import com.tanhua.manage.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 统一token处理拦截器
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("统一token处理拦截器--->前置处理");

        // 1.从请求中获取token
        String token = request.getHeader("Authorization");

        token = token.replace("Bearer ", "");

        if (StringUtils.isEmpty(token)) {
            // 如果token为空，认证失败
            response.setStatus(401);
            return false;
        }

        // 2.根据token获取用户
        Admin admin = adminService.findUserByToken(token);

        if (admin == null) {
            // 如果用户认证失败，返回401
            response.setStatus(401);
            return false;
        }

        // 3.将当前登录用户的信息放到当前线程
        AdminHolder.set(admin);
        return true;
    }
}
